package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.louwowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.member.util.PasswordUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IUserInfoRedisService redisService;

    public boolean checkPhone(String phone) throws LogicException{
        return userInfoMapper.selectCountByPhone(phone) > 0;
    }

    public void sendVerifyCode(String phone) throws LogicException{
        if(!phone.matches("^1[3456789]\\d{9}$")) {
            throw new LogicException("手机号格式不正确，请重新输入");
        }
        //随机生成验证码
        String verifyCode = UUID.randomUUID().toString().substring(0, 4);
        StringBuilder message = new StringBuilder(50);
        //放入redis缓存中
        redisService.setVerifyCode(phone, verifyCode);
        //拼接发送的验证码信息
        message.append("您的验证码：").append(verifyCode).append("，请在3分钟内输入！");
        System.out.println(message);

    }

    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException{
        //非空判断
        AssertUtil.hasLength(phone,"手机号不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断手机号格式是否正确
        ;
        if(!phone.matches("^1[3456789]\\d{9}$")) {
            throw new LogicException("手机号格式不正确，请重新输入");
        }
        //判断手机是否注册
        if (userInfoMapper.selectCountByPhone(phone) > 0) {
            throw new LogicException("手机号已注册");
        }
        //判断两次密码是否一致
        if (!password.equals(rpassword)){
            throw new LogicException("两次密码输入不一致");
        }
        //判断验证码是否正确
        String code = redisService.getVerifyCode(phone);
        if(code == null){
            throw new LogicException("验证码已过期,请重新发送!");
        }
        System.out.println("传入的验证码" + verifyCode);
        AssertUtil.isEquals(verifyCode.toLowerCase(),code.toLowerCase(),"输入的验证码不正确，请重新输入" );
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        //密码加密处理
        String newPassword = null;
        try {
            newPassword = PasswordUtil.getEncrypted(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        userInfo.setPassword(newPassword);
        userInfo.setLevel(1);
        userInfo.setNickname(nickname);
        userInfo.setState(0);
        userInfo.setHeadImgUrl("/images/default.png");
        userInfoMapper.insert(userInfo);
    }

    public String userLogin(String username, String password) throws LogicException{
        String newPassword = null;
        try {
            newPassword = PasswordUtil.getEncrypted(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        UserInfo userInfo = userInfoMapper.selectUserByUsernameAndPassword(username,newPassword);
        //若数据库中没查到登陆的用户信息，则抛出提示
        if(userInfo == null){
            throw new LogicException("账号或密码有错，请重新输入");
        }
        //有该用户的信息，则存入redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisService.setToken(token,userInfo);
        return token;
    }

    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(UserInfo user) {
        if(user == null){
            return;
        }
        if(user.getId() != null){
            userInfoMapper.updateByPrimaryKey(user);
        }else{
            userInfoMapper.insert(user);
        }
    }

    @Override
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateUserHeadImg(UserInfo user) {
        userInfoMapper.updateUserHeadImg(user);
    }

    @Override
    public void updatePasswordByPhone(String phone, String newpassword, String verifyCode) throws LogicException {
        //非空判断
        AssertUtil.hasLength(phone,"手机号不能为空");
        AssertUtil.hasLength(newpassword,"新密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断验证码是否正确
        String code = redisService.getVerifyCode(phone);
        System.out.println("系统的验证码" +code);
        System.out.println("传入的验证码" + verifyCode);
        AssertUtil.isEquals(verifyCode.toLowerCase(),code.toLowerCase(),"输入的验证码不正确，请重新输入" );
        //密码加密处理
        String password = null;
        try {
            password = PasswordUtil.getEncrypted(newpassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
        userInfoMapper.updatePasswordByPhone(phone,password);
    }

    @Override
    public void updateEmailById(Long id, String email, String verifyCode)throws LogicException {
        //非空判断
        AssertUtil.hasLength(email,"邮箱不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断邮箱验证码是否正确
        String code = redisService.getEmailVerifyCode(email);
        System.out.println("系统的验证码" +code);
        System.out.println("传入的验证码" + verifyCode);
        AssertUtil.isEquals(verifyCode.toLowerCase(),code.toLowerCase(),"输入的验证码不正确，请重新输入" );

    }

    @Override
    public boolean checkEmail(String email) throws LogicException {
        return userInfoMapper.selectCountByEmail(email) > 0;
    }

    @Override
    public void sendEmailVerifyCode(String email) throws LogicException {
        //随机生成验证码
        String verifyCode = UUID.randomUUID().toString().substring(0, 6);
        StringBuilder message = new StringBuilder(50);
        //放入redis缓存中
        redisService.setEmailVerifyCode(email, verifyCode);
        //拼接发送的验证码信息
        message.append("您的验证码：").append(verifyCode).append("，请在3分钟内输入！");
        System.out.println(message);
    }

    @Override
    public boolean checkPhoneByVerifyCode(Long id, String phone, String verifyCode) throws LogicException {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(id);
        if(phone != null && userInfo.getPhone().equals(phone)){
            //判断验证码是否正确
            String code = redisService.getVerifyCode(phone);
            System.out.println("系统的验证码" +code);
            System.out.println("传入的验证码" + verifyCode);
            AssertUtil.isEquals(verifyCode.toLowerCase(),code.toLowerCase(),"输入的验证码不正确，请重新输入" );
            return true;
        }
        return false;
    }

    @Override
    public void updatePhoneByVerifyCode(Long id, String phone, String verifyCode) {
        if(phone != null){
            String code = redisService.getVerifyCode(phone);
            System.out.println("系统的验证码" +code);
            System.out.println("传入的验证码" + verifyCode);
            AssertUtil.isEquals(verifyCode.toLowerCase(),code.toLowerCase(),"输入的验证码不正确，请重新输入" );
            userInfoMapper.updatePhoneById(id,phone);
        }
    }

    @Override
    public void delete(UserInfo user, String phone, String verifyCode) throws LogicException {
        if(user == null){
            throw new LogicException("请登录!");
        }
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        AssertUtil.hasLength(phone,"手机号不能为空");
        if(!user.getPhone().equals(phone)){
            throw new LogicException("请使用绑定的手机号注销!");
        }
        String code = redisService.getVerifyCode(phone);
        AssertUtil.hasLength(code,"验证码以过期");
        System.out.println("系统的验证码" +code);
        System.out.println("传入的验证码" + verifyCode);
        AssertUtil.isEquals(verifyCode.toLowerCase(),code.toLowerCase(),"输入的验证码不正确，请重新输入" );
        //注销,把用户的号码加密,邮箱解绑,昵称改为已注销,头像默认
        //麻烦,直接删除
        userInfoMapper.deleteByPrimaryKey(user.getId());

    }
}
